/*global echo pack trim ActiveXObject CreateObject sleep Enumerator
addMenuItem
echo
inputText
sleep
pspadVersion
getVarValue
moduleExists
moduleVersion
moduleFileName
modulePath
closeEditorByTitle
closeEditorByIndex
closeAllEditors
newEditor
editorsCount
setClipboardText
getClipboardText
runPSPadAction
logClear
logAddLine
logGetLine
logSetLine
logLinesCount
projectSave
projectFilesCount
projectFiles
projectFileName
ftpConnect
ftpDisconnect
ftpCommand
ftpDownloadFile
ftpUploadFile
*/

/*jshint strict: false wsh:true unused:false
*/


var menuName = "Wim",
    module_name = "Wim JScript",
    module_ver = "1.2.1",
    globalPattern = "",
    kStrCrlf = "\r\n",
    svnMenuName = "SVN",
    gitMenuName = "GIT",
    logMenuName = "DivaLog",
    fastMMMenuName = "FastMM",
    quoteCharacter = "'";
    

/*
2262:
Script function getVarValue() returns any system variable
Modified script function inputText(label, default, cancel: string): string. If
filled in optional "cancel value", dialog returns it if Cancel button was
pressed.
*/


function Init()
{
  /*jshint white:false*/
  addMenuItem("Convert line to lines", fastMMMenuName, "fastmmConvert");

  addMenuItem("Find in entries", svnMenuName, "findInEntries", "Shift+Ctrl+Alt+F");

  addMenuItem("Pull", gitMenuName, "gitPull");
  addMenuItem("Commit", gitMenuName, "gitCommit",  "Shift+Ctrl+Alt+G");
  addMenuItem("Push", gitMenuName, "gitPush");
  addMenuItem("Sync", gitMenuName, "gitSync");
  addMenuItem("-", gitMenuName, "");
  
  addMenuItem("Open last Diva log"            , logMenuName, "openLastDivaLog"        , "Shift+Ctrl+D"         );
  addMenuItem("Open last HTTP log"            , logMenuName, "openLastHTTPLog"        , "Shift+Ctrl+Alt+1"     );
  addMenuItem("Open last DivaWeb log"         , logMenuName, "openLastDivaWebLog"     , "Shift+Ctrl+Alt+2"     );
  addMenuItem("Open last DivaManager log"     , logMenuName, "openLastDivaManagerLog" , "Shift+Ctrl+Alt+3"     );
  addMenuItem("Open ..."                      , logMenuName, "openDivaLog"            , ""     );
  addMenuItem("-"                             , logMenuName, ""                                              );

  addMenuItem("Paste advance to next line"    , menuName, "pasteNextLine"        , "Shift+Ctrl+X"     );
  addMenuItem("Trim Right"                    , menuName, "trimRightClick"       , "Shift+Ctrl+Alt+T"     );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("Begin Of Word"                 , menuName, "beginOfWord"          , "Shift+Ctrl+Alt+Left"  );
  addMenuItem("End Of Word"                   , menuName, "endOfWord"            , "Shift+Ctrl+Alt+Right" );
  addMenuItem("(Un)Quote Word"                , menuName, "quoteUnquoteWord"     , "Shift+Ctrl+Q"         );
  addMenuItem("(Un)Quote Word Advance"        , menuName, "quoteUnquoteWordAdvance"     , "Shift+Ctrl+Alt+Q"         );
  addMenuItem("Set quote Character"           , menuName, "setQuoteCharacter"                             );
  addMenuItem("Select Word"                   , menuName, "selectWordUnderCursor", "Shift+Ctrl+W"         );
  addMenuItem("Capitalize"                    , menuName, "capitalize"           , "Ctrl+Shift+C"         );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("List js files"                 , menuName, "listJavascriptFiles"                           );
  addMenuItem("openFolder"                    , menuName, "openFolder"                                    );
  addMenuItem("Pack javascript"               , menuName, "packJavaScript"                                );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("Insert Date"                   , menuName, "insertDate"           , "Ctrl+Alt+A"           );
  addMenuItem("Insert comment header"         , menuName, "commentHeader"        , "Shift+Alt+Z"          );
  addMenuItem("format all comment headers"    , menuName, "formatAllCommentHeaders"                       );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("Protect"                       , menuName, "protect"              , "Ctrl+Alt+p"           );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("Clear log"                     , menuName, "clearLog"             , "Shift+Ctrl+L"         );
  addMenuItem("DeleteEmptyLines"              , menuName, "deleteEmptyLines"                              );
  addMenuItem("Comment"                       , menuName, "comment"              , "Ctrl+Alt+."           );
  addMenuItem("Comment Block"                 , menuName, "commentBlock"         , "Shift+Ctrl+R"         );
  addMenuItem("Uncomment"                     , menuName, "uncomment"            , "Ctrl+Alt+,"           );
  addMenuItem("Set comment pattern"           , menuName, "setCommentPattern"                             );
  addMenuItem("Extract lines with marked word", menuName, "extractLines"                                  );
  addMenuItem("Main"                          , menuName, "main"                                          );
  addMenuItem("RemoveSpace"                   , menuName, "removeSpace"                                   );
  addMenuItem("Input"                         , menuName, "input"                                         );
  addMenuItem("Test"                          , menuName, "test"                                          );
  addMenuItem("JScript Help"                  , menuName, "jScriptHelp"                                   );
  addMenuItem("First Line"                    , menuName, "firstLine"            , "Ctrl+Alt+Home"        );
  addMenuItem("Next Line"                     , menuName, "nextLine"             , "Ctrl+Alt+Down"        );
  addMenuItem("Prev Line"                     , menuName, "prevLine"             , "Ctrl+Alt+Up"          );
  addMenuItem("Duplicate Line"                , menuName, "duplicateLine"        , "Ctrl+Alt+PgDn"        );
  addMenuItem("ReadOnly"                      , menuName, "readonly"             , "Ctrl+Alt+R"           );
  addMenuItem("FindToDos"                     , menuName, "findToDos"                                     );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("IntradaToDVIntrada"            , menuName, "intradaToDVIntrada"                            );
  addMenuItem("MethodOnOneLine"               , menuName, "methodOnOneLine"                               );
  addMenuItem("NormalizeIntradaMethods"       , menuName, "normalizeIntradaMethods"                       );
  addMenuItem("LineOutIntradaMethods"         , menuName, "lineOutIntradaMethods"                         );
  addMenuItem("MergeFunction"                 , menuName, "mergeFunction"                                 );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("bug"                           , menuName, "bug"                                           );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("Edit Script File"              , menuName, "openScript"                                    );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("-"                             , menuName, ""                                              );
  addMenuItem("-"                             , menuName, ""                                              );
}

//function ICommon(that){if(that!=null){that.inherit=Common.prototype.inherit;that.specialize=Common.prototype.specialize}return that};ICommon.specialize=function(p,c){if(!p)p={};if(!c)c=p.constructor;if(c=={}.constructor)c=new Function("this.inherit()");c.valueOf=new Function("return this");c.valueOf.prototype=new this.valueOf;c.valueOf.prototype.specialize(p);c.prototype=new c.valueOf;c.valueOf.prototype.constructor=c.prototype.constructor=c;c.ancestor=this;c.specialize=arguments.callee;c.ancestorOf=this.ancestorOf;return c};ICommon.valueOf=new Function("return this");ICommon.valueOf.prototype={constructor:ICommon,inherit:function(){return arguments.callee.caller.ancestor.apply(this,arguments)},specialize:function(that){if(this==this.constructor.prototype&&this.constructor.specialize){return this.constructor.valueOf.prototype.specialize(that)}for(var i in that){switch(i){case"constructor":case"toString":case"valueOf":continue}if(typeof that[i]=="function"&&that[i]!=this[i]){that[i].ancestor=this[i]}this[i]=that[i]}if(that.toString!=this.toString&&that.toString!={}.toString){that.toString.ancestor=this.toString;this.toString=that.toString}return this}};function Common(){};this.Common=ICommon.specialize({constructor:Common,toString:function(){return"[common "+(this.constructor.className||"Object")+"]"},instanceOf:function(klass){return this.constructor==klass||klass.ancestorOf(this.constructor)}});Common.className="Common";Common.ancestor=null;Common.ancestorOf=function(klass){while(klass&&klass.ancestor!=this)klass=klass.ancestor;return Boolean(klass)};Common.valueOf.ancestor=ICommon;function ParseMaster(){var E=0,R=1,L=2;var G=/\(/g,S=/\$\d/,I=/^\$\d+$/,T=/(['"])\1\+(.*)\+\1\1$/,ES=/\\./g,Q=/'/,DE=/\x01[^\x01]*\x01/g;var self=this;this.add=function(e,r){if(!r)r="";var l=(_14(String(e)).match(G)||"").length+1;if(S.test(r)){if(I.test(r)){r=parseInt(r.slice(1))-1}else{var i=l;var q=Q.test(_14(r))?'"':"'";while(i)r=r.split("$"+i--).join(q+"+a[o+"+i+"]+"+q);r=new Function("a,o","return"+q+r.replace(T,"$1")+q)}}_31(e||"/^$/",r,l)};this.exec=function(s){_3.length=0;return _28(_5(s,this.escapeChar).replace(new RegExp(_1,this.ignoreCase?"gi":"g"),_29),this.escapeChar).replace(DE,"")};this.reset=function(){_1.length=0};var _3=[];var _1=[];var _30=function(){return"("+String(this[E]).slice(1,-1)+")"};_1.toString=function(){return this.join("|")};function _31(){arguments.toString=_30;_1[_1.length]=arguments}function _29(){if(!arguments[0])return"";var i=1,j=0,p;while(p=_1[j++]){if(arguments[i]){var r=p[R];switch(typeof r){case"function":return r(arguments,i);case"number":return arguments[r+i]}var d=(arguments[i].indexOf(self.escapeChar)==-1)?"":"\x01"+arguments[i]+"\x01";return d+r}else i+=p[L]}};function _5(s,e){return e?s.replace(new RegExp("\\"+e+"(.)","g"),function(m,c){_3[_3.length]=c;return e}):s};function _28(s,e){var i=0;return e?s.replace(new RegExp("\\"+e,"g"),function(){return e+(_3[i++]||"")}):s};function _14(s){return s.replace(ES,"")}};ParseMaster.prototype={constructor:ParseMaster,ignoreCase:false,escapeChar:""};function pack(_7,_0,_2,_8){var I="$1";_7+="\n";_0=Math.min(parseInt(_0),95);function _15(s){var i,p;for(i=0;(p=_6[i]);i++){s=p(s)}return s};var _25=function(p,a,c,k,e,d){while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p};var _26=function(){if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1}};var _6=[];function _4(p){_6[_6.length]=p};function _18(s){var p=new ParseMaster;p.escapeChar="\\";p.add(/'[^'\n\r]*'/,I);p.add(/"[^"\n\r]*"/,I);p.add(/\/\/[^\n\r]*[\n\r]/," ");p.add(/\/\*[^*]*\*+([^\/][^*]*\*+)*\//," ");p.add(/\s+(\/[^\/\n\r\*][^\/\n\r]*\/g?i?)/,"$2");p.add(/[^\w\x24\/'"*)\?:]\/[^\/\n\r\*][^\/\n\r]*\/g?i?/,I);if(_8)p.add(/;;;[^\n\r]+[\n\r]/);p.add(/\(;;\)/,I);p.add(/;+\s*([};])/,"$2");s=p.exec(s);p.add(/(\b|\x24)\s+(\b|\x24)/,"$2 $3");p.add(/([+\-])\s+([+\-])/,"$2 $3");p.add(/\s+/,"");return p.exec(s)};function _17(s){var p=new ParseMaster;p.add(/((\x24+)([a-zA-Z_]+))(\d*)/,function(m,o){var l=m[o+2].length;var s=l-Math.max(l-m[o+3].length,0);return m[o+1].substr(s,l)+m[o+4]});var r=/\b_[A-Za-z\d]\w*/;var k=_13(s,_9(r),_21);var e=k.e;p.add(r,function(m,o){return e[m[o]]});return p.exec(s)};function _16(s){if(_0>62)s=_20(s);var p=new ParseMaster;var e=_12(_0);var r=(_0>62)?/\w\w+/ :/\w+/;k=_13(s,_9(r),e);var e=k.e;p.add(r,function(m,o){return e[m[o]]});return s&&_27(p.exec(s),k)};function _13(s,r,e){var a=s.match(r);var so=[];var en={};var pr={};if(a){var u=[];var p={};var v={};var c={};var i=a.length,j=0,w;do{w="$"+a[--i];if(!c[w]){c[w]=0;u[j]=w;p["$"+(v[j]=e(j))]=j++}c[w]++}while(i);i=u.length;do{w=u[--i];if(p[w]!=null){so[p[w]]=w.slice(1);pr[p[w]]=true;c[w]=0}}while(i);u.sort(function(m1,m2){return c[m2]-c[m1]});j=0;do{if(so[i]==null)so[i]=u[j++].slice(1);en[so[i]]=v[i]}while(++i<u.length)}return{s:so,e:en,p:pr}};function _27(p,k){var E=_10("e\\(c\\)","g");p="'"+_5(p)+"'";var a=Math.min(k.s.length,_0)||1;var c=k.s.length;for(var i in k.p)k.s[i]="";k="'"+k.s.join("|")+"'.split('|')";var e=_0>62?_11:_12(a);e=String(e).replace(/_0/g,"a").replace(/arguments\.callee/g,"e");var i="c"+(a>10?".toString(a)":"");if(_2){var d=_19(_26);if(_0>62)d=d.replace(/\\\\w/g,"[\\xa1-\\xff]");else if(a<36)d=d.replace(E,i);if(!c)d=d.replace(_10("(c)\\s*=\\s*1"),"$1=0")}var u=String(_25);if(_2){u=u.replace(/\{/,"{"+d+";")}u=u.replace(/"/g,"'");if(_0>62){u=u.replace(/'\\\\b'\s*\+|\+\s*'\\\\b'/g,"")}if(a>36||_0>62||_2){u=u.replace(/\{/,"{e="+e+";")}else{u=u.replace(E,i)}u=pack(u,0,false,true);var p=[p,a,c,k];if(_2){p=p.concat(0,"{}")}return"eval("+u+"("+p+"))\n"};function _12(a){return a>10?a>36?a>62?_11:_22:_23:_24};var _24=function(c){return c};var _23=function(c){return c.toString(36)};var _22=function(c){return(c<_0?'':arguments.callee(parseInt(c/_0)))+((c=c%_0)>35?String.fromCharCode(c+29):c.toString(36))};var _11=function(c){return(c<_0?'':arguments.callee(c/_0))+String.fromCharCode(c%_0+161)};var _21=function(c){return"_"+c};function _5(s){return s.replace(/([\\'])/g,"\\$1")};function _20(s){return s.replace(/[\xa1-\xff]/g,function(m){return"\\x"+m.charCodeAt(0).toString(16)})};function _10(s,f){return new RegExp(s.replace(/\$/g,"\\$"),f)};function _19(f){with(String(f))return slice(indexOf("{")+1,lastIndexOf("}"))};function _9(r){return new RegExp(String(r).slice(1,-1),"g")};_4(_18);if(_8)_4(_17);if(_0)_4(_16);return _15(_7)};

var Editor = (function ()
{
  "use strict";
  var itself;

  itself = function ()
  {
    this.editor = newEditor();
    this.editor.assignActiveEditor();
    this.X = this.editor.caretX();
    this.Y = this.editor.caretY();
  };

  itself.prototype.getLine = function (y)
  {
    this.editor.caretY(y);
    return this.editor.lineText();
  };

  itself.prototype.setLine = function (y, line)
  {
    this.editor.caretY(y);
    this.editor.command("ecLineStart");
    this.editor.lineText(line);
  };

  itself.prototype.restoreCaret = function ()
  {
    this.editor.setCaretPos(this.X, this.Y);
  };
  
  itself.prototype.getSelectedLines = function ()
  {
    var text = this.editor.selText(),
        lines = text.split('\r\n');
        
    if ((lines.length > 0) && (lines[lines.length - 1] === ''))
      lines.splice(lines.length - 1, 1);
    return lines;
  };
  
  itself.prototype.setSelectedLines = function (lines)
  {
    this.editor.selText(lines.join('\r\n') + '\r\n');
  };
  
  itself.prototype.fileName = function ()
  {
    return this.editor.fileName();
  };

  return itself;
}());



function currentFileName()
{
  var ed = new Editor();
  return ed.fileName();
}


/*==================================================================================================
  Description   returns the active editor

  20060904      Wim      Created
==================================================================================================*/
function getActiveEditor()
{
  var editor = newEditor();
  editor.assignActiveEditor();
  return editor;
}


/*==================================================================================================
  Description   Returns the filename portion of the supplied full path filename

  20110503      Wim       Created
==================================================================================================*/
function extractFileName(fileName)
{
  var results = fileName.split('\\');
  return results[results.length - 1];
}


/*==================================================================================================
  Description   Returns the filepath portion of the supplied full path filename

  20110503      Wim       Created
==================================================================================================*/
function extractFilePath(fileName)
{
  var results = fileName.split('\\');
  return results.slice(0, -1).join('\\');
}


/*==================================================================================================
  Description

  20080930      Wim     Created
==================================================================================================*/
function packJavaScript()
{
  var ed = getActiveEditor(),
      text = ed.text();
  text = pack(text, 62, 1, 0);
  ed = newEditor();
  ed.newFile();
  ed.text(text);
}


/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
String.prototype.leftPad = function (size, ch)
{
  var result = this;
  ch = ch || " ";
  while (result.length < size)
  {
    result = ch + result;
  }
  return result;
};

String.prototype.trimRight = function ()
{
  return this.replace(/\s+$/, '');
};


/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
Date.prototype.formatString = function ()
{
  return String(this.getFullYear()) +
         String(this.getMonth() + 1).leftPad(2, "0") +
         String(this.getDate()).leftPad(2, "0");

};



/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function getDateTimeString()
{
  try
  {
    var date = new Date();
    return date.formatString();
  }
  catch (e)
  {
    echo(e.message);
  }
}


/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function insertDate()
{
  var ed = getActiveEditor(),
      now = getDateTimeString() + '      Wim     ';
  ed.selText(now);
}

function gotoFirstNonEmptyLine(ed)
{
  var cnt = ed.linesCount(),
      y = ed.caretY(),
      empty = true,
      line,
      tel = 10;

  while (empty && (y < cnt) && (tel > 0))
  {
    tel += 1;
    line = trim(ed.lineText());
    if (line !== '')
    {
      empty = false;
    }
    else
    {
      y += 1;
      ed.caretY(y);
    }
  }
}

function removeEmptyLinesAboveCurrent(ed)
{
  var y = ed.caretY(),
      line,
      tel = 10,
      empty = true;

  y -= 1;
  while ((y > 0) && (empty) && (tel > 0))
  {
    tel += 1;
    ed.caretY(y);
    line = trim(ed.lineText());

    if (line === '')
    {
      ed.command('ecDeleteLine');
      y -= 1;
    }
    else
    {
      ed.setCaretPos(1, y + 1);
      empty = false;
    }
  }
  return y + 1;
}


/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function prevLineIsComment(ed)
{
  var result = false,
      y = ed.caretY(),
      line;
  if (y > 0)
  {
    ed.caretY(y - 1);
    line = ed.lineText();
    if (line.search("=======") === 0)
    {
      result = true;
    }
    ed.caretY(y);
  }
  return result;
}




/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function commentHeader()
{
  var ed = getActiveEditor(),
      line,
      newline;
  gotoFirstNonEmptyLine(ed);
  removeEmptyLinesAboveCurrent(ed);
  if (!prevLineIsComment(ed))
  {
    line = ed.lineText();
    newline = '';
    newline += '\n';
    newline += '\n';
    if (line.search(/\/\*========/) !== 0)
    {
//      newline += '/*==================================================================================================\n';
//      newline += '  Description\n';
//      newline += '  \n';
//      newline += '  ' + getDateTimeString() + '      Wim       Created\n';
//      newline += '==================================================================================================*/\n';
      newline += '/*=============================================================================================*//**\n';
      newline += '  Description\n';
      newline += '*///================================================================================================\n';
    }
    newline += line;
    ed.lineText(newline);
  }
  ed.caretX(1);
}

function insertEmptyLines(ed, cnt)
{
  var line = ed.lineText();
  line = '\n\n' + line;
  ed.lineText(line);
}

function logLine(y, ed)
{
  var oy = ed.caretY(),
      line;
  ed.caretY(y);
  line = ed.lineText();
  ed.caretY(oy);
  logAddLine(y + ': ' + line);
}


function formatAllCommentHeaders()
{
  var ed = getActiveEditor(),
      y = 1,
      currentY = ed.caretY(),
      cnt = ed.linesCount(),
      line;

  while (y < cnt)
  {
    ed.caretY(y);
    line = ed.lineText();
    if (line.search(/\/\*========/) === 0)
    {
      y = removeEmptyLinesAboveCurrent(ed);
      if (y > 1)
      {
        insertEmptyLines(ed, 2);
        y += 2;
      }
    }
    y += 1;
    cnt = ed.linesCount();
  }
  ed.caretY(currentY);
}


/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function TLogInfo(line)
{
  var txt = line,
      pos = txt.search(/\[Lint\]/);

  this.file = '';
  this.line = 0;
  this.col = 0;

  if (pos >= 0)
  {
    txt = txt.substr(pos + 6);
    pos = txt.search(/\(/);
    if (pos >= 0)
    {
      this.file = trim(txt.substr(0, pos));
      txt = txt.substr(pos + 1, txt.length);
      pos = txt.search(/,/);
      if (pos)
      {
        this.line = trim(txt.substr(0, pos));
        txt = txt.substr(pos + 1, txt.length);
        pos = txt.search(/\)/);
        if (pos >= 0)
        {
          this.col = trim(txt.substr(0, pos));
        }
      }
    }
  }

  this.info = function ()
  {
    return this.file + ',    ' + this.line + ',    ' + this.col;
  };
}


/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function protect()
{
  var ed = getActiveEditor(),
      line = ed.lineText(),
      begin = line.indexOf(".exe"),
      end,
      ch,
      newline;
  if (begin >= 0)
  {
    begin += 4;
    end = line.length - 1;
    ch = line.charAt(end);
    while (((('0' <= ch) && (ch <= '9')) || (ch === ';')) && (end > begin))
    {
      end -= 1;
      ch = line.charAt(end);
    }
    if (end > begin)
    {
      newline = line.substr(0, begin) + ', Codes=' + line.substr(end);
      ed.lineText(newline);
      ed.command("ecScrollDown");
      ed.command("ecDown");
      ed.command("ecLineEnd");
    }
  }
}


/*==================================================================================================
  Description

  20080620      Wim       Created
==================================================================================================*/
function bug()
{
  var ed = getActiveEditor(),
      s;
  ed.command("ecLineStart");
  s = ed.lineText();
  ed.command("ecLineStart");
  ed.lineText(s);
}


/*==================================================================================================
  Description   Clears the log window

  20080409      Wim      Created
==================================================================================================*/
function clearLog()
{
  logClear();
}



function readonly()
{
  //var mes = "";
  var count = editorsCount(),
      ed = newEditor(),
      i,
      ro,
      sro;

  for (i = 0; i !== count; i += 1)
  {
    ed.assignEditorByIndex(i);
    ro = ed.readOnly(false);
    sro = ro ? "Readonly" : "";
    //mes = mes + ed.fileName() + String(":  ") + sro + kStrCrlf ;
  }
  //echo (mes);
}




/*==================================================================================================
  Description   retrieves the text of the active line in the editor

  20060904      Wim      Created
==================================================================================================*/
function getLine(editor, y)
{
  editor.caretY(y);
  return editor.lineText();
}

/*==================================================================================================
  Description   set the text of the active line in the editor

  20060904      Wim      Created
==================================================================================================*/
function setLine(editor, y, line)
{
  editor.caretY(y);
  //editor.caretX(0);
  editor.command("ecLineStart");
  editor.lineText(line);
}

/*==================================================================================================
  Description   increases the active line in the editor

  20060904      Wim      Created
==================================================================================================*/
function setNextLine(editor)
{
  if (editor.caretY() < editor.linesCount())
  {
    editor.caretY(editor.caretY() + 1);
  }
}

/*==================================================================================================
  Description   decreases the active line in the editor

  20060904      Wim      Created
==================================================================================================*/
function setPrevLine(editor)
{
  if (editor.caretY() > 1)
  {
    editor.caretY(editor.caretY() - 1);
  }
}


/*==================================================================================================
  Description   makes the first line in the active editor the active line

  20060904      Wim      Created
==================================================================================================*/
function firstLine()
{
  var ed = getActiveEditor();
  ed.caretY(1);
}

/*==================================================================================================
  Description   advance to the next line in the active editor

  20060904      Wim      Created
==================================================================================================*/
function nextLine()
{
  setNextLine(getActiveEditor());
}

/*==================================================================================================
  Description   goto the previous line in the active editor

  20060904      Wim      Created
==================================================================================================*/
function prevLine()
{
  setPrevLine(getActiveEditor());
}

/*==================================================================================================
  Description   copy the active line in the active editor

  20060904      Wim      Created
==================================================================================================*/
function duplicateLine()
{
  var ed = getActiveEditor(),
      thisLine = ed.lineText();
  thisLine = thisLine + "\r\n" + thisLine;
  ed.lineText(thisLine);
  nextLine();
}

function removeTrash()
{
  firstLine();
  //var ed = getActiveEditor();

}



function removeSpace()
{
  var ed = newEditor();
  ed.assignActiveEditor();
  echo(ed.getSelText);
}

function main()
{
  //var obj = newEditor();
  echo(menuName);
  //obj.text("hallo wim");
}

function input()
{
  var obj = newEditor();
  obj.input("hoi");
}

function openScript()
{
  var editor = newEditor();
  editor.openFile(moduleFileName(module_name));
}

function jScriptHelp()
{
  var sh = new ActiveXObject("WScript.shell");
  sh.Run('http://gogogadgetscott.info/pspad/functions.htm');
}

function test()
{
  var str = '/*======================',
      pos = str.search(/\/\*========/);
  echo(pos);
}



/*==================================================================================================
  Description   Comment/uncomment all lines with pattern

  20070302      Wim      Created
==================================================================================================*/
function setCommentPattern()
{
  globalPattern = getActiveEditor().selText();
}


/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
function getPattern()
{
  var patterns =
  {
    tex: '%',
    sty: '%',
    py: '#'
  },
  ed,
  name,
  parts,
  ext,
  result = globalPattern;

  if (result === '' || result === undefined)
  {
    ed = getActiveEditor();
    name = ed.fileName();
    parts = name.split('.');
    ext = parts[parts.length - 1].toLowerCase();
    result = patterns[ext];

    if (result === undefined)
    {
      result = '//';
    }
  }
  return result;
}


/*==================================================================================================
  Description   Comment/uncomment all lines with pattern

  20070302      Wim      Created
==================================================================================================*/
function comment()
{
  var sourceEditor = getActiveEditor(),
      selText = sourceEditor.selText(),
      lines = selText.split("\n"),
      pattern = getPattern(),
      i;

  for (i = 0; i < lines.length - 1; i += 1)
  {
    lines[i] = pattern + lines[i];
  }
  selText = lines.join("\n");
  sourceEditor.selText(selText);
}


/*=============================================================================================*//**
  Description
*///================================================================================================
function commentBlock()
{
  var editor, text; 
  
  try
  {
    editor = getActiveEditor();
    text = editor.selText();
    if (text !== '')
    {
      if (text.match(/\/\*.*\*\//))
        text = text.substring(2, text.length - 2);
      else
        text = '/*' + text + '*/';
      editor.selText(text);
    }
  }
  catch (e)
  {
    logAddLine(e.message);
  }
}


/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
function uncomment()
{
  var sourceEditor = getActiveEditor(),
      selText = sourceEditor.selText(),
      lines = selText.split("\n"),
      pattern = getPattern(),
      i,
      line,
      iPos;

  for (i = 0; i < lines.length - 1; i += 1)
  {
    line = lines[i];
    iPos = line.indexOf(pattern);
    if (iPos === 0)
    {
      line = line.substring(pattern.length, line.length);
    }
    lines[i] = line;
  }
  selText = lines.join("\n");
  sourceEditor.selText(selText);
}



/*==================================================================================================
  Description   Find lines with "Using" or "using" and put them in a new editor

  20060904      Wim      Created
==================================================================================================*/
function extractLines()
{
  var sourceEditor = getActiveEditor(),
      destEditor = newEditor(),
      word = sourceEditor.selText(),
      i,
      line,
      pos;
  destEditor.newFile();

  for (i = 0; i < sourceEditor.linesCount(); i += 1)
  {
    line = getLine(sourceEditor, i);
    pos = line.indexOf(word);
    if (pos >= 0)
    {
      destEditor.appendText(line + "\n");
    }
  }
}


/*
Sub prefixComment()
Dim objEditor, item
Set objEditor = newEditor()
objEditor.assignActiveEditor()
For Each item in objEditor
item = "'" & item
Next
End Sub


*/



function trimRight(value)
{
  return value.replace(/\s+$/, '');
}
/*==================================================================================================
  Description   Trims a value

  20070926      Wim      Created
==================================================================================================*/
function trim(value)
{
  value = value.replace(/^\s+/, '');
  // / delimiter: start
  // ^ begin of line
  // \s whitespace
  // + all characters
  // / delimiter: end

  value = value.replace(/\s+$/, '');
  return value;
}

/*==================================================================================================
  Description   Returns strings last character

  20070926      Wim      Created
==================================================================================================*/
function lastChar(line)
{
  return line.charAt(line.length - 1);
}


/*==================================================================================================
  Description   Maakt van een functie op meerdere regels 1 regel
                Kijkt of het laatste karakter van de regel een komma is

                zolang laatste karakter van getrimmde regel een komma is dan:
                    Spatie achter komma
                    VolgendeRegel.TrimLeft
                    VolgendeRegel achter spatie
                daarna naar VolgendeRegel

  abracadabra simsalabim(iets anders,
                         volgende parameter,
                         nog* een);

  wordt
  abracadabra simsalabim(iets anders,volgende parameter,nog* een);

  20060904      Wim      Created
==================================================================================================*/
function doMergeFunction(editor)
{
  var regel = editor.caretY(),
      nextregel = regel,
      breaker = 20,
      thisLine = trimRight(getLine(editor, regel)),
      i;

  while ((lastChar(thisLine) === ',') && (breaker > 0))
  {
    breaker = breaker - 1;
    nextregel = nextregel + 1;
    nextLine = getLine(editor, nextregel);
    thisLine = thisLine + ' ' + trim(nextLine);
  }

  setLine(editor, regel, thisLine);
  for (i = regel + 1; i <= nextregel;  i += 1)
  {
    editor.CaretY(regel + 1);
    editor.command("ecDeleteLine");
  }
  editor.caretY(regel + 1);
  editor.caretX(0);
}
function mergeFunction()
{
  doMergeFunction(getActiveEditor());
}

/*==================================================================================================
  Description   Removes all empty lines from current line position

  20070926      Wim      Created
==================================================================================================*/
function doDeleteEmptyLines(editor)
{
  var breaker = 20,
      regel = editor.caretY(),
      thisLine = trim(getLine(editor, regel));

  while ((thisLine.length === 0) && (breaker > 0) && (regel < editor.linesCount()))
  {
    breaker -= 1;
    editor.command("ecDeleteLine");
    thisLine = trim(getLine(editor, regel));
  }
}
function deleteEmptyLines()
{
  doDeleteEmptyLines(getActiveEditor());
}



function mergeFunctions(lines)
{
  var i,
      line,
      ni;

  for (i = 0; i !== lines.length - 1; i += 1)
  {
    line = trimRight(lines[i]);
    ni = i + 1;
    if (lastChar(line) === ',')
    {
      line = line + ' ' + trim(lines[ni]);
      lines[ni] = '';
      ni += 1;
      while ((lastChar(line) === ',') && (ni < lines.length))
      {
        line = line + ' ' + trim(lines[ni]);
        lines[ni] = '';
        ni += 1;
      }
      lines[i] = line;
      i = ni -= 1;
    }
  }
}

/*==================================================================================================
  Description

  20070927      Wim      Created
==================================================================================================*/
function linesToText(lines)
{
  var result = '',
      count = lines.length,
      i;

  if (count)
  {
    result = result + lines[0];
    for (i = 1; i !== count; i += 1)
    {
      result = result + '\n' + lines[i];
    }
  }
  return result;
}


/*==================================================================================================
  Description

  20070927      Wim      Created
==================================================================================================*/
function linesToTextWithOutEmptyLines(lines)
{
  var result = '',
      count = lines.length,
      index;

  if (count)
  {
    index = 0;
    while (lines[index].length === 0 && index < count)
    {
      index += 1;
    }
    if (index < count)
    {
      result = result + lines[index];
      index += 1;
      while (index < count)
      {
        if ((lines[index].length > 0) && (lines[index].charCodeAt(0) !== 13))
        {
          result = result + '\n' + lines[index];
        }
        index += 1;
      }
    }
  }
  return result;
}
/*==================================================================================================
  Description

  20070926      Wim      Created
==================================================================================================*/
function spaces(count)
{
  var result = '',
      i;

  for (i = 0; i !== count; i += 1)
  {
    result += ' ';
  }

  return result;
}
/*==================================================================================================
  Description   LineOutIntradaMethods ( and )

  20070926      Wim      Created
==================================================================================================*/
function doLineOutEx(lines, delimiter)
{
  var line,
      lline,
      max = 0,
      count = lines.length,
      leftValues,
      rightValues,
      result,
      i;

  if (count > 100)
  {
    count = 100;
  }
  leftValues = [];
  rightValues = [];
  result = [];
  for (i = 0; i !== count; i += 1)
  {
    line  = lines[i];
    lline = line.split(delimiter);
    leftValues[i] = lline[0];
    rightValues[i] = lline[1];
    if (max < leftValues[i].length && leftValues[i] !== lines[i])
    {
      max = leftValues[i].length;
    }
  }
  for (i = 0; i !== count; i += 1)
  {
    //Result[i] = LeftValues[i] + Spaces(Max - LeftValues[i]) + delimiter + RightValues[i]
    result[i] = leftValues[i];
    if (rightValues[i])
    {
      result[i] += spaces(max - leftValues[i].length) + delimiter + rightValues[i];
    }
  }
  return result;
}

/*==================================================================================================
  Description

  20070927      Wim      Created
==================================================================================================*/
function doLineOut(lines, delimiter, column)
{
  var pos,
      result = 0,
      count = lines.length,
      i;

  if (count > 1000)
  {
    count = 1000;
  }

  for (i = 0; i !== count; i += 1)
  {
    pos = lines[i].indexOf(delimiter, column);
    if ((pos >= 0) && (result < pos))
    {
      result = pos;
    }
  }
  for (i = 0; i !== count; i += 1)
  {
    if (lines[i].length > 0)
    {
      pos = lines[i].indexOf(delimiter, column);
      if (pos >= 0)
      {
        lines[i] = lines[i].substring(0, pos) + spaces(result - pos) + lines[i].substring(pos, 99999);
      }
    }
  }
  return result;
}

/*==================================================================================================
  Description   return everthing before the first ( (trimmed)
                CreateAreaImage (IntradaData data, int area, IntradaImage *image);
                CreateAreaImage

  20070927      Wim      Created
==================================================================================================*/
function extractMethod(line)
{
  var result = line,
      pos = result.indexOf('(');

  if (pos >= 0)
  {
    result = trim(result.substring(0, pos));
  }
  return result;
}



/*==================================================================================================
  Description   return everthing between the first ( )
                extern int IntradaCreateAreaImage (IntradaData data, int area, IntradaImage *image);
                (IntradaData data, int area, IntradaImage *image)

  20070927      Wim      Created
==================================================================================================*/
function extractParams(line)
{
  var result = line,
      begin = line.indexOf('('),
      eind = line.indexOf(')');

  if ((begin >= 0) && (eind > begin))
  {
    result = result.substring(begin, eind + 1);
  }
  return result;
}

/*==================================================================================================
  Description   Removes the types from the args
                (HBITMAP hbitmap, int to_gray, IntradaImage *image)
                (data, area, image)

  20070927      Wim      Created
==================================================================================================*/
function removeTypes(line)
{
  var len = line.length,
      result = trim(line),
      begin = 0,
      eind,
      cont,
      breaker = 50;

  if (result.charAt(0) === '(')
  {
    result = result.substring(1, 9999);
    cont = 1;
    begin = 0;
    eind = begin;
    while (cont && (breaker > 0))
    {
      breaker -= 1;
      while ((result.charAt(eind) === ' ') || (result.charAt(eind) === '*'))
      {
        result = result.substring(0, begin) + result.substring(eind + 1, 9999);
      }
      while ((result.charAt(eind) !== ' ') && (result.charAt(eind) !== ',') && (result.charAt(eind) !== ')') && (eind < len))
      {
        eind += 1;
      }
      if (result.charAt(eind) === ' ')
      {
        result = result.substring(0, begin) + result.substring(eind + 1, 9999);
        eind = begin;
      }
      else if (result.charAt(eind) === ',')
      {
        begin = eind + 1;
        eind = begin;
      }
      else
      {
        cont = 0;
      }
    }
    result = '(' + result;
  }
  return result;
}


/*==================================================================================================
  Description

  20070927      Wim      Created
==================================================================================================*/
function convertIntradaLine(line)
{
  var result = line,
      delim = "extern int Intrada",
      pos = result.indexOf(delim, 0),
      method,
      params,
      args;

  if (pos === 0)
  {
    result = trim(result.substring(delim.length, 9999));
    method = extractMethod(result);
    params = extractParams(result);
    args = removeTypes(params);
    result = '  INTRADA_DEF (' + method + ',' + params + ',' + args + ');';
  }
  return result;
}

/*==================================================================================================
  Description

  20070927      Wim      Created
==================================================================================================*/
function doNormalizeIntradaMethods(lines)
{
  var count = lines.length,
      i;

  if (count > 1000)
  {
    count = 1000;
  }
  for (i = 0; i !== count; i += 1)
  {
    lines[i] = convertIntradaLine(lines[i]);
  }
}

function normalizeIntradaMethods()
{
  var result,
      editor = getActiveEditor(),
      lines = editor.selText().split("\n");

  doNormalizeIntradaMethods(lines);

  result = linesToText(lines);
  editor.selText(result);
}



/*==================================================================================================
  Description   Calls MergeFunction and DeleteEmptyLines

  20070926      Wim      Created
==================================================================================================*/
function methodOnOneLine()
{
  var editor = getActiveEditor(),
      lines = editor.selText().split("\n"),
      result;

  mergeFunctions(lines);

  result = linesToTextWithOutEmptyLines(lines);
  editor.selText(result);
}



/*==================================================================================================
  Description
                INTRADA_DEF (BitmapToImage,(HBITMAP hbitmap, int to_gray, IntradaImage * image)(hbitmap,to_gray,image));


  20070927      Wim      Created
==================================================================================================*/
function doLineOutIntradaMethods(lines)
{
  var column = 15;
  column = doLineOut(lines, ',(', column);
  column = doLineOut(lines, '),(', column);
  column = doLineOut(lines, '));', column);
}
function LineOutIntradaMethods()
{
  var editor = getActiveEditor(),
      lines = editor.selText().split("\n"),
      result;

  doLineOutIntradaMethods(lines);
  result = linesToTextWithOutEmptyLines(lines);
  editor.selText(result);
}



/*==================================================================================================
  Description

  20070927      Wim      Created
==================================================================================================*/
function intradaToDVIntrada()
{
  var editor = getActiveEditor(),
      lines = editor.selText().split("\n"),
      result;

  mergeFunctions(lines);
  doNormalizeIntradaMethods(lines);
  doLineOutIntradaMethods(lines);

  result = linesToTextWithOutEmptyLines(lines);
  editor.selText(result);
}


/*

module_name = "HTML AutoInclude";
module_ver = "0.1";
// Code copyright 2006 T, Pattison. Please contact me via
// geniscope.atspace.com with any ammendments or enhancements to this
// script.

// This script updates the contents of the current HTML file with matching
// blocks within the "include.html" file.
// This script expects a file called "include.html" to be present within
// the open project.
// Blocks are identified by pairs of HTML comments:
// <!-- name -->[newline]X number of Lines of HTML[newline]<!-- Endname -->
// Script takes named comment from include.html and searches for the same
// comment within the current file.

function GetBlocks(){
  logwin = NewEditor();
  logwin.AssignLog();
  var editor = newEditor();
  editor.assignActiveEditor();
  curFile=editor.fileName();
  logwin.appendText("Updating: "+curFile+"\n");
  var obj2 = newEditor();
  obj2.openFile("include.html");
  obj2.command("ecNormalSelect");
  iText = obj2.Text();
  ilines = iText.split("\n");
  var inBlk=0;
  for (var ii=0; ii<ilines.length; ii++) {
    if (inBlk==0) {
    obj2.setCaretPos(0,ii+1);
      if (ilines[ii].indexOf("<!-- ")>=0) {
        if (ilines[ii].indexOf("<!-- End")==-1) {
          var cmtEnd=ilines[ii].indexOf("->");
          Blk=ilines[ii].substring(5,(cmtEnd-2));
          logwin.appendText("Finding: *"+Blk+"*"+"\n");
          inBlk=1;
        }
        else {logwin.appendText("Error in include.html\n");}
      }
    }
    if (inBlk==1) {
      obj2.command("ecSelDown");
      if (ilines[ii].indexOf("<!-- End"+Blk)>=0) {
        inBlk=0;
        obj2.command("ecSelUp");
        //ready to copy
        obj2.command("ecCopy");
        GotoMark(Blk);
      }
    }
  }
  if (inBlk==1){logwin.appendText("Error in include.html: file ends before end comment found\n");}
  obj2 = null;
  logwin.appendText("Done!\n");
}

function GotoMark(Blk){
    pattern = "<!-- "+Blk+" -->";
    stPos = GetStrPos(pattern);
    pattern = "<!-- End"+Blk+" -->";
    enPos = GetStrPos(pattern);
    var editor = newEditor();
    editor.assignEditorByName(curFile);
    editor.command("ecLineStart");
    editor.command("ecNormalSelect");
    if(enPos>stPos && stPos>=0 && enPos>=0){
        editor.setCaretPos(0,stPos);
        for (var kk=0; kk<(enPos-stPos); kk++) {
            editor.command("ecSelDown");
        }
        editor.command("ecPaste");
    }
    else{
        logwin.appendText("No match found for "+Blk+"\n");
    }
    editor = null;
}
todo: hier

function GetStrPos(pattern){
    var editors = newEditor();
    editors.assignEditorByName(curFile);
    allText = editors.Text();
    lines = allText.split("\n");
    var iPos=0;
    var StrPosn = -1;
    for (var jj=0; jj<lines.length; jj++) {
        iPos = lines[jj].indexOf(pattern);
        if(iPos != -1){
            StrPosn = jj+1;
            logwin.appendText("Valid comment found at line "+StrPosn+"\n");
            return (StrPosn);
            break;
        }
    }
    editors = null;
}

function Init(){
  addMenuItem("Update Include", "HTML AutoInclude", "GetBlocks");
}
*/


/*
  var FS     = CreateObject("Scripting.FileSystemObject");
  var Shell  = CreateObject("Shell.Application");
  var ed = getActiveEditor();
  var fileName = ed.fileName();

  var File   = FS.GetFile(fileName);
  var folderName = File.ParentFolder;
  Shell.Explore(folderName)
  echo(folderName);
*/


/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
function findToDos()
{
  var sH = new CreateObject("WScript.Shell");
  sH.AppActivate("PSPad");
  sleep(100);
  // Send Alt + F
  sH.SendKeys("^f");
  sleep(100);
  sH.SendKeys("todo");
  sleep(100);
  // Sends the shortcut for the ok button. = Alt+O
  sH.SendKeys("%l");
}


function wordLeft()
{
  var ed = getActiveEditor();

  ed.command("ecWordLeft");
}
function wordRight()
{
  var ed = getActiveEditor();

  ed.command("ecWordRight");
}


/*==================================================================================================
  Description

  20090604      Wim     Created
==================================================================================================*/
function doSelectWordUnderCursor(quoted)
{
  var ed = getActiveEditor(),
      line = ed.lineText(),
      curx = ed.caretX(),
      //cury = ed.caretY(),
      //cursymb,
      i, begPos, endPos,
      len = line.length,
      regex = quoted ? /['\w]/ : /\w/;

  i = curx - 1; //positions in line begin from 1 not from 0
  while ((line.charAt(i).match(regex)) && (i < len))
  {
    i += 1;
  }
  endPos = i - 1; //cycle ended when i point for one position over edge
  i = curx - 1;

  //backtrack one position if no char found to see if we are at end of word.
  if ((!line.charAt(i).match(regex)) && (i >= 0))
  {
    i -= 1;
  }

  while ((line.charAt(i).match(regex)) && (i >= 0))
  {
    i -= 1;
  }
  begPos = i + 1; //cycle ended when i points for one position under edge
  ed.caretX(begPos + 1); //return to string index (from 1, not from 0 as in String)
  len = endPos - begPos + 1; // substract that belong low edge, not low edge itself
  for (i = 0; i < len; i += 1)
  {
    ed.command("ecSelRight");
  }
}
/*
alpha

  dit 'is' leuk
  'dit ''is'' leuk'

  beta

  gamma delta

    epsilon
*/

/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
function selectWordUnderCursor()
{
  doSelectWordUnderCursor(false);
}


/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
function setQuoteCharacter()
{
  quoteCharacter = inputText("Enter a quote character", quoteCharacter, quoteCharacter);
}

function quoteUnquoteWord()
{
  var ed = getActiveEditor(),
      saveX = ed.caretX(),
      text = ed.selText(),
      word;

  logClear();

  if (text.length === 0)
  {
    doSelectWordUnderCursor(true);
  }
  word = ed.selText();
  if (word.length > 0)
  {
    if (word.charAt(0) === "'")
    {
      word = word.substr(1, word.length - 2);
      //saveX -= 1;
    }
    else
    {
      word = quoteCharacter + word + quoteCharacter;
      //saveX += 1;
    }
    ed.selText(word);
    ed.caretX(saveX);
  }
}


function quoteUnquoteWordAdvance()
{
  quoteUnquoteWord();
  var ed = getActiveEditor();
  ed.command('ecScrollDown');
  ed.command('ecDown');
}


function quoteWordA()
{
  var ed = getActiveEditor(),
      line = ed.lineText(),
      curX = ed.caretX(),
      saveX = curX,
      //curY = ed.caretY(),
      len = line.length,
      //curSym,
      index, begin, end;

  logClear();

  index = curX - 1;
  logAddLine('[' + line + ']');
  logAddLine('curX: ' + curX);
  logAddLine('index: ' + index);
  while ((line.charAt(index).match(/\w/)) && (index < len))
  {
    index += 1;
  }
  logAddLine('index: ' + index);

  if (curX > index && index > 0)
  {
    saveX = curX;
    ed.command("ecWordLeft");
    curX = ed.caretX();
    index = curX - 1;
    while ((line.charAt(index).match(/\w/)) && (index < len))
    {
      index += 1;
    }
    ed.caretX(saveX);
  }
  logAddLine('index: ' + index);

  end = index; //cycle ended when i point for one position over edge
  logAddLine('index: ' + index);
  index = curX - 1;
  while ((line.charAt(index).match(/\w/)) && (index >= 0))
  {
    index -= 1;
  }
  begin = index + 1; //cycle ended when i points for one position under edge

  line = line.substring(0, begin) + "'" + line.substring(begin, end) + "'" + line.substring(end, line.length);
  logAddLine('[' + line + ']');
  ed.caretX(3);
  ed.lineText(line);
  ed.caretX(saveX + 1);
}


/*==================================================================================================
  Description

  20090508      Wim     Created
==================================================================================================*/
function capitalize()
{
  try
  {
    var ed = getActiveEditor(),
        line = ed.lineText(),
        curx = ed.caretX(),
        i,
        ch,
        beginPos;

    i = curx - 2;
    while ((line.charAt(i).match(/\w/)) && (i >= 0))
    {
      i -= 1;
    }
    beginPos = i + 2;
    ed.caretX(beginPos);
    ed.command("ecSelRight");
    ch = ed.selText();
    ch = ch <= 'Z' ? ch.toLowerCase() : ch = ch.toUpperCase();
    ed.selText(ch);
    ed.caretX(curx);
  }
  catch (errB)
  {
    echo(errB.message);
  }
}



function beginOfWord()
{
  var ed = getActiveEditor(),
      line = ed.lineText(),
      curx = ed.caretX(),
      begPos,
      //len = line.length,
      regex = /\w/;

  begPos = curx - 2; //positions in line begin from 1 not from 0
  while ((line.charAt(begPos).match(regex)) && (begPos >= 0))
  {
    begPos -= 1;
  }
  curx = begPos + 2;
  ed.caretX(curx);
}

function endOfWord()
{
  var ed = getActiveEditor(),
      line = ed.lineText(),
      curx = ed.caretX(),
      endPos,
      len = line.length,
      regex = /\w/;

  logClear();
  endPos = curx - 1; //positions in line begin from 1 not from 0
  while ((line.charAt(endPos).match(regex)) && (endPos < len))
  {
    endPos += 1;
  }
  curx = endPos + 1;
  ed.caretX(curx);
}

function listJavascriptFiles()
{
  var i, l, fileName, pos;

  logClear();
  for (i = 0, l = projectFilesCount(); i < l; i += 1)
  {
    fileName = projectFiles(i);
    pos = fileName.search('\\.js');
    if (pos !== -1 && pos === fileName.length - 3)
    {
      logAddLine(fileName);
    }
  }
}



function openFolder()
{
  var shell = CreateObject("Shell.Application");
      dir = extractFilePath(currentFileName());
  shell.Explore(dir);  
}


/*=============================================================================================*//**
  Opens last file in logdir that matches pattern
*///================================================================================================
function openLastLog(logdir, pattern)
{
  var fileSystem, folder, folderFiles, files, file, editor, path;

  files = [];
  fileSystem = new ActiveXObject("Scripting.FileSystemObject");
  folder = fileSystem.GetFolder(logdir);
  folderFiles = new Enumerator(folder.files);

  for (; !folderFiles.atEnd(); folderFiles.moveNext())
  {
    path = folderFiles.item().Path;
    if (path.match(pattern))
    {
      files.push(path);
    }
  }
  files.sort();
  file = files.pop();

  editor = newEditor();
  editor.openFile(file);
}


/*=============================================================================================*//**
  Description
*///================================================================================================
function openLastDivaLog()
{
  openLastLog("C:\\Users\\Wim\\AppData\\Roaming\\Diva\\Log", "DivaLog");
/*  
  var logdir, fileSystem, folder, folderFiles, files, file, editor, path;

  logdir = "C:\\Users\\Wim\\AppData\\Roaming\\Diva\\Log";
  files = [];
  fileSystem = new ActiveXObject("Scripting.FileSystemObject");
  folder = fileSystem.GetFolder(logdir);
  folderFiles = new Enumerator(folder.files);

  for (; !folderFiles.atEnd(); folderFiles.moveNext())
  {
    path = folderFiles.item().Path;
    if (path.match('DivaLog'))
    {
      files.push(path);
    }
  }
  files.sort();
  file = files.pop();

  editor = newEditor();
  editor.openFile(file);
*/
}


/*=============================================================================================*//**
  Description
*///================================================================================================
function openLastHTTPLog()
{
  openLastLog("C:\\Users\\Wim\\AppData\\Roaming\\Diva\\Log\\Plugins", "HTTP ");
}


/*=============================================================================================*//**
  Description
*///================================================================================================
function openLastDivaWebLog()
{
  openLastLog("C:\\Users\\Wim\\AppData\\Roaming\\Diva\\Log\\Plugins", "DivaWeb ");
}


/*=============================================================================================*//**
  Description
*///================================================================================================
function openLastDivaManagerLog()
{
  openLastLog("C:\\Users\\Wim\\AppData\\Roaming\\Diva\\Log\\Plugins", "DivaManager ");
}


/*=============================================================================================*//**
  Description
*///================================================================================================
function openDivaLog()
{
  try
  {
    runPSPadAction("aOpen");
//    var wshShell, objDialog, appDataPath;
//    
//    logClear();
//    wshShell = new ActiveXObject("WScript.shell");
//    appDataPath = wshShell.SpecialFolders.Item("AppData") + "\\Diva\\Log";
//    logAddLine("1");
//    objDialog = new ActiveXObject("MSComDlg.CommonDialog");
//    logAddLine("2");
//    objDialog.InitialDir = appDataPath;
//    logAddLine("3");
//    objDialog.Filter = "All files (*.*)|*.*;Log files (*.txt)|*.txt;Log files (*.log)|*.log";
//    logAddLine("4");
//    if (objDialog.ShowOpen())
//    {
//      echo(objDialog.FileName);
//    }
//    else
//    {
//      echo("cancelled");
//    }
//    logAddLine("5");
  }
  catch (err)
  {
    echo(err.message);
  }
}


/*==================================================================================================
  Description

  20101117      Wim       Created
==================================================================================================*/
function commaTime(line)
{
  var result, posb, pose;

  result = line;
  if (line !== '')
  {
    if (line.charAt(line.length - 2) === ')')
    {
      posb = line.lastIndexOf('(');
      pose = line.lastIndexOf(')');
      if ((posb >= 0) && (pose > posb))
      {
        result = line.substring(0, posb) + '; ' + line.substring(posb + 1, pose) + line.substring(pose + 1, line.length);
      }
    }
  }
  return result;
}


function showFilesInDirectory(directory)
{
  //see http://ns7.webmasters.com/caspdoc/html/jscript_language_reference.htm
  //and http://ns7.webmasters.com/caspdoc/html/jscript_folder_object_files_property.htm
  var fs, f, fc, s;

  fs = new ActiveXObject("Scripting.FileSystemObject");
  f = fs.GetFolder(directory);
  fc = new Enumerator(f.files);
  s = "";
  for (; !fc.atEnd(); fc.moveNext())
  {
    s += fc.item();
    s += "\n";
    //s += "<br>";
  }
  //WScript.Echo(s);
}

/*
  var FS     = CreateObject("Scripting.FileSystemObject");
  var Shell  = CreateObject("Shell.Application");
  var ed = getActiveEditor();
  var fileName = ed.fileName();

  var File   = FS.GetFile(fileName);
  var folderName = File.ParentFolder;
  Shell.Explore(folderName)
  echo(folderName);
*/


/*==================================================================================================
  Description   Searches text in entries files in given directory and subfolders.

  First line is text to find.
  Second line is selected directory (includes subdirectories).

  Example:
  svn://connect/DivaSource/Trunk
  E:\SVN\DivaSource\WorkingCopy

  20101126      Wim       Created
==================================================================================================*/
function findInEntries()
{
  var sourceEditor = getActiveEditor(),
      selText = sourceEditor.selText(),
      lines = selText.split("\n"),
      dir, str,
      Shell;

  logClear();
  logAddLine(WScript.ScriptFullName);

  if (lines.length > 1)
  {
    str = lines.shift();
    dir = lines.shift();

    logAddLine("Text to find: " + str);
    logAddLine("Selected directory: " + dir);
  }

  try
  {
    Shell  = new CreateObject("Shell.Application");
    Shell.Explore(dir);
    //logAddLine('');
  }
  catch (e)
  {
    logAddLine(e);
    logAddLine(e.message);
  }
}


/*==================================================================================================
  Description

  20110317      Wim       Created
==================================================================================================*/
function fastmmConvert()
{
  var ed = getActiveEditor(),
      text = ed.selText();

  text = text.replace(/ @ /g, "\n");
  ed.selText(text);
}


/*==================================================================================================
  Description

  20110503      Wim       Created
==================================================================================================*/

function gitCommand(command)
{
  var exe, cmd, path, wshShell, exec;

  exe  = '"C:\\Program Files\\TortoiseGit\\bin\\TortoiseGitProc.exe"';
  cmd  = "/command:" + command;
  path = '/path:"' + extractFilePath(currentFileName()) + '"';
  exec = exe + ' ' + cmd + ' ' + path + ' /notempfile';

  wshShell = new ActiveXObject("WScript.shell");
  //wshShell.Run(exe + ' ' + cmd + ' ' + path + ' /notempfile');
  try
  {
    wshShell.Run(exec);
  }
  catch (e)
  {
    logAddLine('Exception: "' + e.message + '"');
  }
}

function gitPull()
{
  gitCommand("pull");
}
function gitCommit()
{
  gitCommand("commit");
}
function gitPush()
{
  gitCommand("push");
}
function gitSync()
{
  gitCommand("sync");
}

function pasteNextLine()
{
  var ed = getActiveEditor(),
      curx = ed.caretX(),
      cury = ed.caretY();
  ed.command('ecPaste');
  ed.setCaretPos(curx, cury + 1);  
}



/*==================================================================================================
  Description

  20110530      Wim       Created
==================================================================================================*/
function trimRightClick()
{
  var sourceEditor, text, lines, newlines, allText;

  sourceEditor = getActiveEditor();
  allText = false;
  text = sourceEditor.selText();
  if (text === '')
  {
    allText = true;
    text = sourceEditor.text();
  }
  lines = text.split("\n");
  newlines = [];

  while (lines.length > 0)
  {
    try
    {
      newlines.push(trimRight(lines.shift()));
    }
    catch (e)
    {
      logAddLine(e.message);
    }
  }
  text = newlines.join("\n");
  if (allText)
    sourceEditor.text(text);
  else
    sourceEditor.selText(text);
}



